document.addEventListener('DOMContentLoaded', function () {
    // 获取需要更新的页面元素
    const brokerCountEl = document.getElementById('brokerCount');
    const topicCountEl = document.getElementById('topicCount');
    const totalMessagesEl = document.getElementById('totalMessages');
    const tpsEl = document.getElementById('tps');
    const refreshStatusEl = document.getElementById('refresh-status');

    // 获取i18n文本的辅助函数
    const getI18nText = (key, fallback) => {
        const element = document.querySelector(`[data-i18n="${key}"]`);
        return element ? element.textContent : fallback;
    };

    // 定义一个异步函数来获取和更新数据
    const updateDashboard = async () => {
        try {
            const response = await fetch('/api/cluster-overview');
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.statusText}`);
            }
            const data = await response.json();

            // 更新页面上的数据
            brokerCountEl.textContent = data.brokerCount;
            topicCountEl.textContent = data.topicCount;
            totalMessagesEl.textContent = data.totalMessages;
            tpsEl.textContent = data.tps.toFixed(2);

            // 更新状态指示器为“成功”状态
            const liveUpdateText = getI18nText('dashboard.live.update', 'Live Update');
            refreshStatusEl.innerHTML = '<span class="spinner-grow spinner-grow-sm text-success" role="status" aria-hidden="true"></span> ' + liveUpdateText;
        } catch (error) {
            console.error('Failed to fetch dashboard data:', error);
            // 更新状态指示器为“失败”状态
            const updateFailedText = getI18nText('dashboard.update.failed', 'Update Failed');
            refreshStatusEl.innerHTML = '<span class="spinner-grow spinner-grow-sm text-danger" role="status" aria-hidden="true"></span> ' + updateFailedText;
        }
    };

    // 设置一个定时器，每 5 秒调用一次 updateDashboard 函数
    setInterval(updateDashboard, 5000);
}); 
